package pl.edu.pw.ee.buildcity.charts;

import org.apache.commons.lang.time.DateUtils;
import org.junit.Test;
import org.mockito.Mockito;
import pl.edu.pw.ee.buildcity.commons.exceptions.BuildCityRuntimeException;
import pl.edu.pw.ee.buildcity.domain.BuildStatus;
import pl.edu.pw.ee.buildcity.entities.BuildActivity;
import pl.edu.pw.ee.buildcity.services.BuildActivityService;

import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static org.mockito.BDDMockito.given;
import static pl.edu.pw.ee.buildcity.charts.ChartsGenerator.NUMBER_OF_ACTIVITIES_TO_FETCH;
import static pl.edu.pw.ee.buildcity.domain.BuildStatus.FAILED;
import static pl.edu.pw.ee.buildcity.domain.BuildStatus.SUCCEEDED;


/**
 * @author Mateusz
 * @since 2010-02-17
 */
public class ChartsTestGenerator {

	private ChartsGenerator chartsGenerator;

	@Test
	public void shouldGenerateProperURLToGoogleCharts() {
		//Given
		BuildActivityService mockBuildActivityService = Mockito.mock(BuildActivityService.class);

		List<BuildActivity> buildActivities = generateBuildActivities(NUMBER_OF_ACTIVITIES_TO_FETCH);
		given(mockBuildActivityService.getLatestBuildActivities("myBuild", NUMBER_OF_ACTIVITIES_TO_FETCH)).willReturn(buildActivities);

		chartsGenerator = new ChartsGenerator();
		chartsGenerator.setBuildActivityService(mockBuildActivityService);

		//When
		String url = chartsGenerator.durationOfLatestBuildActivities("myBuild");

		//Then
		try {
			java.awt.Desktop.getDesktop().browse(new URL(url).toURI());
		} catch (Exception e) {
			throw new BuildCityRuntimeException(e);
		}
	}

	private List<BuildActivity> generateBuildActivities(int numberOfActivitiesToGenerate) {
		List<BuildActivity> buildActivities = new ArrayList<BuildActivity>();

		for (int i = 0; i < numberOfActivitiesToGenerate; i++) {

			Date started = DateUtils.addSeconds(new Date(), -1000 - i);
			BuildActivity buildActivity = new BuildActivity().started(started).ended(new Date());
			BuildStatus status = i % 2 == 0 ? SUCCEEDED : FAILED;
			buildActivity.setResult(status);
			buildActivities.add(buildActivity);
		}
		return buildActivities;
	}
}
